package com.example.controller;

import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.*;
import java.util.List;

/**
 * @author 吕一明
 * @公众号 码客在线
 */
@RestController
public class UserController {

    @Autowired
    UserRepository userRepository; // JpaRepositoryFactoryBean

    @PersistenceContext
    private EntityManager em;

    @GetMapping("/1")
    public Object test1() {

        return userRepository.findByOrderByIdDesc();
    }

    @GetMapping("/2")
    public Object test2() {
        return userRepository.findByNameStartingWithAndAgeLessThan("平", 19);
    }//分%

    @GetMapping("/3")
    public Object test3() {
        return userRepository.findNameById(1L);
    }

    @GetMapping("/4")
    public void test4() {
        userRepository.deleteByNameAndAge("tom", 11);
    }

    @GetMapping("/5")
    public Object test5() {
        Pageable pageable = PageRequest.of(0, 2);
        Page<User> page = userRepository.findByNameOrderByIdDesc(pageable,"吕一明");
        return page;
    }

    /**
     * root 查询的类型
     * query 查询条件
     * cb 构建Predicate
     * @return
     */
    @GetMapping("/6")
    public Object test6() {

        Sort sort = new Sort(Sort.Direction.ASC, "id");

        Pageable pageable = PageRequest.of(0, 5, sort);

        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path path = root.get("name");

                Predicate predicate1 = criteriaBuilder.equal(path, "一明");
                Predicate predicate2 = criteriaBuilder.equal(path, "一明");
                Predicate predicate3 = criteriaBuilder.equal(path, "一明");
                Predicate predicate4 = criteriaBuilder.equal(path, "一明");
                return criteriaBuilder.and(predicate1, predicate2, predicate3);
            }
        };

        Page<User> page = userRepository.findAll(specification, pageable);

        return page;

    }

}
